from fastapi import HTTPException

from app.config import settings, CacheType
from app.core.cache.memory_cache import AsyncMemoryCache
from app.core.cache.redis_cache import AsyncRedisCache
from app.utils.decorators.singleton import singleton


@singleton
class CacheFactory:
    """缓存工厂类 (单例模式)"""
    def __init__(self):
        self._instance = None

    def get_cache(self):
        if settings.CACHE_TYPE == CacheType.REDIS:
            if self._instance is None:
                self._instance = AsyncRedisCache(
                    host=settings.REDIS_HOST,
                    port=settings.REDIS_PORT,
                    db=settings.REDIS_DB,
                    password=settings.REDIS_PASSWORD,
                    prefix=settings.REDIS_PREFIX,
                )
                print("{0:-^100}".format("已启用Redis缓存"))
            else:
                print("{0:-^100}".format("已存在Redis缓存，直接返回"))
            return self._instance
        else:
            if self._instance is None:
                self._instance = AsyncMemoryCache()
                print("{0:-^100}".format("已启用本地缓存"))
            else:
                print("{0:-^100}".format("已存在本地缓，直接返回"))
            return self._instance

    def get_cache_instance(self):
        """手动获取缓存实例"""
        try:
            return self.get_cache()
        except Exception as e:
            raise HTTPException(500, f"获取缓存服务失败：{str(e)}")

    async def close(self):
        if self._instance:
            await self._instance.close()
            self._instance = None

